package com.bbs.exception;

import com.bbs.utils.Constants;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.net.BindException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ControllerExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public String handleConstraintViolationException(ConstraintViolationException exception){
        return exception.getLocalizedMessage().substring(exception.getLocalizedMessage().indexOf(":")+1);
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, String> handleException(Exception ex){
        //debug
        ex.printStackTrace();

        Map<String, String> exceptionMap = new HashMap<>();
        exceptionMap.put("code", Constants.GLOBAL_EXCEPTION_CODE);
        exceptionMap.put("message", Constants.GLOBAL_EXCEPTION_MESSAGE);
        return exceptionMap;
    }

    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Map<String, String> handleMyException(BusinessException myex){
        myex.printStackTrace();

        Map<String, String> myExceptionMap = new HashMap<>();
        myExceptionMap.put("message", myex.getMessage());
        myExceptionMap.put("code", myex.getCode());
        return myExceptionMap;
    }

    @ResponseBody
    @ExceptionHandler(value = AccessDeniedException.class)
    public Map<String, String> handleAccessDeniedException(AccessDeniedException e){
        e.printStackTrace();

        Map<String, String> myExceptionMap = new HashMap<>();
        myExceptionMap.put("message", Constants.FORBIDDEN_MESSAGE);
        myExceptionMap.put("code", Constants.FORBIDDEN_CODE);
        return myExceptionMap;
    }
}
